<?php

/**
 * Class Api
 *
 * @author Steffen Brem <steffenbrem@gmail.com>
 */
class Api
{
    /**
     * @var \Api\Application
     */
    protected $api;

    /**
     * @var Api
     */
    public static $shared;

    /**
     * @param $namespace
     * @param $path
     */
    public function __construct($namespace, $path)
    {
        self::$shared = $this;

        include "Api/Application.php";

        $config = array(
            'application' => array(
                'mode' => \Api\Application::MODE_DEPENDENT
            )
        );

        $this->api = new \Api\Application($namespace, $path, $config);
    }

    /**
     * @return \Api\Application
     */
    public function getApi()
    {
        return $this->api;
    }

    /**
     * Run API
     */
    public function run()
    {
        $this->api->run();
    }

    /**
     * @param $resource
     * @param null $identifier
     * @param string $rpc
     * @param array $body
     * @param array $params
     * @return array
     */
    public function request($resource, $identifier = null, $rpc = '__read', array $body = array(), array $params = array())
    {
        $request = new \Api\Http\Request(null, $params);
        $request->setResource($resource);
        $request->setIdentifier($identifier);
        $request->setRpc($rpc);
        $request->setPayload($body);

        $this->api->bootstrap->setRequest($request);
        $r = $this->api->bootstrap->dispatch();

        if ($r instanceof \Api\Http\Response)
        {
            return $r->getData();
        }

        return $r;
    }
}